<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/actions/qualitydepartmentemployee/QualityDepartmentEmployeeAction.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/actions/Response.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/Service.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/entities/Process.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/const/Error.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/const/Pattern.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/utils/Str.php';
require_once $_SERVER['DOCUMENT_ROOT'].'/model/Service/ServiceFactory.php';

final class ProcessUpdateAction extends QualityDepartmentEmployeeAction {
	protected function execute(Response $response) {
		$process = null;
		if(isset($_POST['code']) &&
				Str::isMatch(Pattern::PROCESS_CODE, $_POST['code']) &&
				isset($_POST['name']) &&
				Str::isMatch(Pattern::NAME, $_POST['name']) &&
				isset($_POST['object']) &&
				Str::isMatch(Pattern::SENTENCE, $_POST['object'])){
			$process = new Process();
			$process->setCode($_POST['code']);
			$process->setName($_POST['name']);
			$process->setObject($_POST['object']);
			
			$serviceFactory = new ServiceFactory();
			$servicePost = $serviceFactory->getService('PostService');
			$owner = $servicePost->read($_POST['id_owner']);
			$process->setOwner($owner);
			
			$service = $serviceFactory->getService('ProcessService');
			if(isset($_POST['id_process'])) {
				$process->setIdentity($_POST['id_process']);
			} 
			$process= $service->save($process);
			if($process === null) {
				$response->setError(Error::UNIQUE_PROCESS_ERROR);
			}
		}
		if($response->getError() === null) {
			if($process !== null) {
				$_SESSION['id_process'] = $process->getIdentity();
				$response->setActionPath('/editing/process/edit.html');
			} else {
				$response->setActionPath('/editing/process/index.html');
			}
		}
	}
}
?>